# 使用 Ubuntu 22.04 作为基础镜像
FROM ubuntu:22.04

# 设置环境变量
ENV DEBIAN_FRONTEND=noninteractive

# 设置工作目录
WORKDIR /app

# 替换为阿里云镜像源
RUN sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list

# 更新包管理器并安装必要的依赖
RUN apt-get update && apt-get install -y \
    wget \
    curl \
    gnupg \
    lsb-release \
    ca-certificates \
    software-properties-common \
    && rm -rf /var/lib/apt/lists/*

# 添加 MongoDB 官方 GPG 密钥（使用更可靠的方法）
RUN wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | gpg --dearmor -o /usr/share/keyrings/mongodb-server-6.0.gpg

# 添加 MongoDB 6.0 仓库
RUN echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-6.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-6.0.list

# 更新包管理器并安装 MongoDB 工具
RUN apt-get update && apt-get install -y \
    mongodb-mongosh \
    mongodb-database-tools \
    && rm -rf /var/lib/apt/lists/*

# 复制本地mongosync文件到容器中
COPY mongosync-ubuntu2404-x86_64-*.tgz /tmp/mongosync.tgz

# 解压并安装mongosync
RUN tar -xzf /tmp/mongosync.tgz -C /tmp && \
    ls -la /tmp && \
    find /tmp -maxdepth 1 -type d -name "*mongosync*" -exec mv {} /tmp/mongosync-extracted \; && \
    ls -la /tmp/mongosync-extracted && \
    mv /tmp/mongosync-extracted/bin/mongosync /usr/local/bin/ && \
    chmod +x /usr/local/bin/mongosync && \
    rm -rf /tmp/mongosync.tgz /tmp/mongosync-extracted

# 创建非root用户
RUN useradd -m -s /bin/bash mongosync \
    && mkdir -p /home/mongosync/scripts \
    && chown -R mongosync:mongosync /home/mongosync

# 复制配置文件和脚本
COPY config.json /home/mongosync/
COPY sync-scripts/ /home/mongosync/scripts/
RUN chmod +x /home/mongosync/scripts/*.sh && \
    chown -R mongosync:mongosync /home/mongosync

# 切换到非root用户
USER mongosync

# 设置工作目录
WORKDIR /home/mongosync

# 验证安装
RUN mongosync --version

# 设置默认命令
CMD ["sleep", "10000"] 